<template>
	<view class="container">
		<uni-nav-bar left-icon="back" status-bar :fixed="true" title="设备信息" right-text="断开连接" backgroundColor="#0081ff"
			color="white" @clickLeft="goBack" @clickRight="cancleConnect" size="24">
		</uni-nav-bar>
		<uni-segmented-control :current="current" :values="items" @clickItem="onClickItem" activeColor="#0081ff"
			styleType="text" class="segment-tabs"></uni-segmented-control>
		<view class="content">
			<view v-show="current === 0">
				<view :class="['read_btns', { nodiag: !isDiagnosis }]">
					<view class="scan_left">
						<button type="default" class="grades">100</button>
						<view class="scan-text" v-if="!isDiagnosis">
							<h4 class="scaning">点击一键诊断</h4>
							<text>获取设备主控、仓控、检测单元等状态信息哦~</text>
						</view>
						<view class="scan-text" v-else>
							<h4 class="scaning">智能扫描中</h4>
							<text>正在诊断监控项~</text>
						</view>
					</view>
					<button class="read_btn" v-if="!isProcess && isDiagnosis" @click="isRead">
						一键诊断
					</button>
					<button v-if="isProcess" class="read_btn">诊断中...</button>
				</view>
				<view class="diognosis-btns">
					<u-button v-if="!isDiagnosis" class="dg-btn" @click="isRead">一键诊断</u-button>
				</view>
				<view v-if="isDiagnosis">
					<view class="cards param-content" id="poster">
						<u-collapse :accordion="false">
							<u-collapse-item title="主控状态" :open="true">
								<u-cell-group :border="false">
									<u-cell-item title="网络状态:" :arrow="false"
										:value="NETWORK[masterControl.param1] || masterControl.param1"
										:value-style="{color: comColor(masterControl.param1)}">
									</u-cell-item>
									<u-cell-item title="信号强度:" :arrow="false" :value="masterControl.param2">
									</u-cell-item>
									<u-cell-item title="主平台连接状态:" :arrow="false"
										:value="PLATFORM_CONNECT[masterControl.param3] || masterControl.param3"
										:value-style="{color: comColor(masterControl.param3)}">
									</u-cell-item>
									<u-cell-item title="运维平台连接状态:" :arrow="false"
										:value="PLATFORM_CONNECT[masterControl.param4] || masterControl.param4"
										:value-style="{color: comColor(masterControl.param4)}">
									</u-cell-item>
									<u-cell-item title="ICCID:" :arrow="false" :value="masterControl.param5">
									</u-cell-item>
									<u-cell-item title="整柜禁用状态:" :arrow="false"
										:value="IS_ENABLE[masterControl.param6] ||masterControl.param6"
										:value-style="{color: comColor2(masterControl.param6)}">
									</u-cell-item>
									<u-cell-item title="故障信息:" :arrow="false" :value="masterControl.param7">
									</u-cell-item>
								</u-cell-group>
							</u-collapse-item>
							<u-collapse-item title="仓状态" :open="true">
								<view class="bin-card">
									<view class="bin-one" v-for="(one, index) in Number(binNum)" :key="index"
										:is-shadow="false">
										<view class="bin-border" @click="binPopup(index)">{{ index + 1 }}号仓</view>
									</view>
								</view>
							</u-collapse-item>
							<u-collapse-item title="检测单元状态信息" :open="true">
								<view class="bin-card">
									<view class="bin-one box-one" v-for="(one,index) in comCabinNum" :key="index"
										:is-shadow="false">
										<view class="bin-border" @click="unitPopup(index)">检测单元{{index+1}}</view>
									</view>
								</view>
							</u-collapse-item>
						</u-collapse>
					</view>
				</view>
			</view>
			<view v-show="current === 1 || current === 2">
				<view class="param-contents">
					<u-card v-for="(one, index) in paramItems" :key="index" :title="one"
						@click="goPage(index)"></u-card>
				</view>
			</view>
		</view>
		<!-- 仓详情 弹框 -->
		<uni-popup ref="binpopup" type="center" class="bin_popup" :animation="false" :is-mask-click="false">
			<view class="alertbox binpopbox">
				<uni-icons class="closeempty" type="closeempty" size="30" color="#6A6A6A"
					@click="closeBinpopup('binpopup')"></uni-icons>
				<view class="binparam">
					<view class="bin_left">
						{{ currentIndex }}号仓
					</view>
					<view class="bin_right">
						<view class="binone">
							<text class="labels">仓状态：</text>
							<text
								:style="{color: comColor(binStatus.param1)}">{{ CABIN_STATUS[binStatus.param1] ||  binStatus.param1}}</text>
						</view>
						<view class="binone">
							<text class="labels">充电电压：</text>
							<text>{{ binStatus.param2 }}V</text>
						</view>
						<view class="binone">
							<text class="labels">充电电流：</text>
							<text>{{ binStatus.param3 }}A</text>
						</view>
						<view class="binone">
							<text class="labels">有功功率：</text>
							<text>{{ binStatus.param4 }}W</text>
						</view>
						<view class="binone">
							<text class="labels">有功电能：</text>
							<text>{{ binStatus.param5 }}kW·h</text>
						</view>
						<view class="binone">
							<text class="labels">输出继电器状态：</text>
							<text
								:style="{color: comColor2(binStatus.param6)}">{{ RELAY_STATUS[binStatus.param6] || binStatus.param6 }}</text>
						</view>
						<view class="binone">
							<text class="labels">风机状态：</text>
							<text :style="{color: comColor(binStatus.param6)}" v-if="binStatus.param7 == 0">停止</text>
							<text v-else>{{binStatus.param7}}rpm</text>
						</view>
						<view class="binone">
							<text class="labels">加热部件状态：</text>
							<text
								:style="{color: comColor2(binStatus.param8)}">{{ HEAT1[binStatus.param8] ||  binStatus.param8}}</text>
						</view>
						<view class="binone">
							<text class="labels">实时温度：</text>
							<text>{{ binStatus.param9 }}℃</text>
						</view>
						<view class="binone">
							<text class="labels">仓门状态：</text>
							<text
								:style="{color: comColor2(binStatus.param10)}">{{ DOOR_STATUS[binStatus.param10] || binStatus.param10}}</text>
						</view>
						<view class="binone">
							<text class="labels">禁用状态：</text>
							<text
								:style="{color: comColor2(binStatus.param11)}">{{ IS_ENABLE[binStatus.param11] ||binStatus.param11}}</text>
						</view>

						<h5 class="label-title">故障信息</h5>
						<view class="binone">
							<text class="labels">输出过压：</text>
							<text
								:style="{color: comColor2(binStatus.param12)}">{{ IS_NORMAL[binStatus.param12] || binStatus.param12}}</text>
						</view>
						<view class="binone">
							<text class="labels">输出欠压：</text>
							<text
								:style="{color: comColor2(binStatus.param13)}">{{ IS_NORMAL[binStatus.param13] || binStatus.param13}}</text>
						</view>
						<view class="binone">
							<text class="labels">输出过流：</text>
							<text
								:style="{color: comColor2(binStatus.param14)}">{{ IS_NORMAL[binStatus.param14] || binStatus.param14}}</text>
						</view>
						<view class="binone">
							<text class="labels">仓低温：</text>
							<text
								:style="{color: comColor2(binStatus.param15)}">{{ IS_NORMAL[binStatus.param15] || binStatus.param15}}</text>
						</view>
						<view class="binone">
							<text class="labels">充电超时(充电时间大于最长充电时间)：</text>
							<text
								:style="{color: comColor2(binStatus.param16)}">{{ IS_NORMAL[binStatus.param16] || binStatus.param16}}</text>
						</view>
						<view class="binone">
							<text class="labels">非法开门：</text>
							<text
								:style="{color: comColor2(binStatus.param17)}">{{ IS_NORMAL[binStatus.param17] || binStatus.param17}}</text>
						</view>
						<view class="binone">
							<text class="labels">继电器状态异常(吸合不上或者断不开)：</text>
							<text
								:style="{color: comColor2(binStatus.param18)}">{{ IS_NORMAL[binStatus.param18] || binStatus.param18}}</text>
						</view>
						<view class="binone">
							<text class="labels">充电设备未正常连接(单位时间内检测到设备)：</text>
							<text
								:style="{color: comColor2(binStatus.param19)}">{{ IS_NORMAL[binStatus.param19] || binStatus.param19}}</text>
						</view>
						<view class="binone">
							<text class="labels">心跳超时(主控心跳超时)：</text>
							<text
								:style="{color: comColor2(binStatus.param20)}">{{ IS_NORMAL[binStatus.param20] || binStatus.param20}}</text>
						</view>
						<view class="binone">
							<text class="labels">仓过温：</text>
							<text
								:style="{color: comColor2(binStatus.param21)}">{{ IS_NORMAL[binStatus.param21] || binStatus.param21}}</text>
						</view>
						<view class="binone">
							<text class="labels">输出过载：</text>
							<text
								:style="{color: comColor2(binStatus.param22)}">{{ IS_NORMAL[binStatus.param22] || binStatus.param22}}</text>
						</view>
						<view class="binone">
							<text class="labels">暂停充电：</text>
							<text
								:style="{color: comColor2(binStatus.param23)}">{{ IS_NORMAL[binStatus.param23] || binStatus.param23}}</text>
						</view>
						<view class="binone">
							<text class="labels">仓门打开异常：</text>
							<text
								:style="{color: comColor2(binStatus.param24)}">{{ IS_NORMAL[binStatus.param24] || binStatus.param24}}</text>
						</view>
						<view class="binone">
							<text class="labels">消防启动：</text>
							<text
								:style="{color: comColor2(binStatus.param25)}">{{ IS_NORMAL[binStatus.param25] || binStatus.param25}}</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<!-- 检测单元 弹框-->
		<uni-popup ref="unitpopup" type="center" class="bin_popup" :animation="false" :is-mask-click="false">
			<view class="alertbox binpopbox">
				<uni-icons class="closeempty" type="closeempty" size="30" color="#6A6A6A"
					@click="closeBinpopup('unitpopup')"></uni-icons>
				<view class="binparam">
					<view class="bin_left">
						检测单元{{ currentIndex }}
					</view>
					<u-cell-group :border="false">
						<u-cell-item title="柜门状态：" :arrow="false"
							:value="`${CABIN_DOOR_STATUS[unitInfo.param1] || unitInfo.param1}`"
							:value-style="{color: comColor(unitInfo.param1)}">
						</u-cell-item>
						<u-cell-item title="供电状态：" :arrow="false"
							:value="`${POWER_SUPPLY_STATUS[unitInfo.param2] || unitInfo.param2}`"
							:value-style="{color: comColor(unitInfo.param2)}">
						</u-cell-item>
						<u-cell-item title="烟感状态：" :arrow="false"
							:value="`${SMOKE_DETECTOR[unitInfo.param3] ||unitInfo.param3}`"
							:value-style="{color: comColor2(unitInfo.param3)}">
						</u-cell-item>
						<u-cell-item title="环境温度：" :arrow="false" :value="`${unitInfo.param4}°C`">
						</u-cell-item>
						<u-cell-item title="水浸状态：" :arrow="false"
							:value="`${WATER_OUT[unitInfo.param5] || unitInfo.param5}`"
							:value-style="{color: comColor2(unitInfo.param3)}">
						</u-cell-item>
						<u-cell-item title="风扇状态：" :arrow="false"
							:value="`${IS_ENABLED[unitInfo.param6] || unitInfo.param6}`"
							:value-style="{color: comColor(unitInfo.param6)}">
						</u-cell-item>
						<u-cell-item title="电表有功电量：" :arrow="false" :value="`${unitInfo.param7}`">
						</u-cell-item>
						<u-cell-item title="电表电压：" :arrow="false" :value="`${unitInfo.param8}`">
						</u-cell-item>
						<u-cell-item title="电表电流：" :arrow="false" :value="`${unitInfo.param9}`">
						</u-cell-item>
						<u-cell-item title="电表有功功率：" :arrow="false" :value="`${unitInfo.param10}`">
						</u-cell-item>


						<h5 class="label-title warn-title">故障信息：</h5>
						<view class="warn-cell">
							<u-cell-item title="烟雾告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param11] || unitInfo.param11}`"
								:value-style="{color: comColor2(unitInfo.param11)}">
							</u-cell-item>
							<u-cell-item title="消防告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param12] || unitInfo.param12}`"
								:value-style="{color: comColor2(unitInfo.param12)}">
							</u-cell-item>
							<u-cell-item title="消防启动:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param13] || unitInfo.param13}`"
								:value-style="{color: comColor2(unitInfo.param13)}">
							</u-cell-item>
							<u-cell-item title="水浸告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param14] || unitInfo.param14}`"
								:value-style="{color: comColor2(unitInfo.param14)}">
							</u-cell-item>
							<u-cell-item title="防雷告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param15] || unitInfo.param15}`"
								:value-style="{color: comColor2(unitInfo.param15)}">
							</u-cell-item>

							<u-cell-item title="漏保告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param16] || unitInfo.param16}`"
								:value-style="{color: comColor2(unitInfo.param16)}">
							</u-cell-item>
							<u-cell-item title="风扇异常告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param17] || unitInfo.param17}`"
								:value-style="{color: comColor2(unitInfo.param17)}">
							</u-cell-item>
							<u-cell-item title="异常断电告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param18] || unitInfo.param18}`"
								:value-style="{color: comColor2(unitInfo.param18)}">
							</u-cell-item>
							<u-cell-item title="过流保护:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param19] || unitInfo.param19}`"
								:value-style="{color: comColor2(unitInfo.param19)}">
							</u-cell-item>
							<u-cell-item title="输入过压告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param20] || unitInfo.param20}`"
								:value-style="{color: comColor2(unitInfo.param20)}">
							</u-cell-item>
							<u-cell-item title="输入低压告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param21] || unitInfo.param21}`"
								:value-style="{color: comColor2(unitInfo.param21)}">
							</u-cell-item>
							<u-cell-item title="消防电池欠压告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param22] || unitInfo.param22}`"
								:value-style="{color: comColor2(unitInfo.param22)}">
							</u-cell-item>
							<u-cell-item title="电表通讯异常告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param23] || unitInfo.param23}`"
								:value-style="{color: comColor2(unitInfo.param23)}">
							</u-cell-item>
							<u-cell-item title="系统过温告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param24] || unitInfo.param24}`"
								:value-style="{color: comColor2(unitInfo.param24)}">
							</u-cell-item>
							<u-cell-item title="系统过载告警:" :arrow="false"
								:value="`${IS_NORMAL[unitInfo.param25] || unitInfo.param25}`"
								:value-style="{color: comColor2(unitInfo.param25)}">
							</u-cell-item>
						</view>
					</u-cell-group>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		ab2hex,
		hexCharCodeToStr,
		doCopy,
		calculateCRC16,
		strLength,
		sendAuthString
	} from "@/utils/index.js";
	import {
		base64ToPath
	} from "image-tools";
	import {
		mapState
	} from "vuex";

	import detailjs from "./detail.js";
	import {
		authPassword,
		serviceId,
		characteristicId1,
		characteristicId2,
	} from "@/utils/service.js";

	import {
		getLockOption,
		batteryIsOn,

		NETWORK,
		PLATFORM_CONNECT,
		IS_ENABLE,
		IS_ONLINE,
		POWER_CHANGE,
		IS_WARN,
		IS_ENABLED,
		HEAT1,
		ABNORMAL_OUTAGE,
		FLOODLIGHT,
		MAINTAIN_DOOR,
		WATER_FEEDBACK,
		SMOKE_STATUS,
		IS_START,
		IS_FAULT,
		IS_NORMAL,
		OVETRCURRENT,
		IS_DORMANT,
		CURRENT_LIMIT,
		IS_AUTO,
		IS_FORBIDDEN,
		BATERRY_TYPE,
		RUN_STATUS,
		UNDERVOL,
		UPVOL,
		HIGHTEM,
		PRESSURE,
		MOS_STATUS,
		BMS_STATUS,
		IS_DOORS,
		IS_CHARGE,
		CHARGE_CURRENT,
		OVER_CURRENT,
		VOL_LOSE,
		NOTALLOW_CHARGE,
		BATTERY_ONLINE,
		LOAD_PROTECT,
		UP_VOL_PROTECT,
		CURRENT_LIMIT_WARN,
		CELL_HIGH_TEM,
		ENVIR_LOW_TEM,
		ENVIR_HIGH_TEM,
		MOS_HIGH_TEM,
		LOW_VOL_PROTECT,
		INVERSE_PROTECT,
		BMS_SIGN,
		MOS_PIPE_STATUS,
		BATTERY_ADJUST,
		BATTERY_STATUSING,
		BATTERY_CONTROL,
		DOOR_STATUS,
		BATTERY_ISON,
		DOOR_LOCK_SIGNAL,
		CABIN_STATUS,
		RELAY_STATUS,
		CABIN_DOOR_STATUS,
		POWER_SUPPLY_STATUS,
		SMOKE_DETECTOR,
		WATER_OUT,
	} from "@/common/config.js";
	export default {
		mixins: [detailjs],
		data() {
			return {
				show: false,
				device: null,
				deviceInfo: {},

				deviceType: null, //设备类型
				binNum: 0, //仓数

				getLockOption: getLockOption,
				batteryIsOn: batteryIsOn,

				NETWORK: NETWORK,
				PLATFORM_CONNECT: PLATFORM_CONNECT,
				IS_ENABLE: IS_ENABLE,
				IS_ONLINE: IS_ONLINE,
				POWER_CHANGE: POWER_CHANGE,
				IS_WARN: IS_WARN,
				IS_ENABLED: IS_ENABLED,
				HEAT1: HEAT1,
				ABNORMAL_OUTAGE: ABNORMAL_OUTAGE,
				FLOODLIGHT: FLOODLIGHT,
				MAINTAIN_DOOR: MAINTAIN_DOOR,
				WATER_FEEDBACK: WATER_FEEDBACK,
				SMOKE_STATUS: SMOKE_STATUS,
				IS_START: IS_START,
				IS_FAULT: IS_FAULT,
				IS_NORMAL: IS_NORMAL,
				OVETRCURRENT: OVETRCURRENT,
				IS_DORMANT: IS_DORMANT,
				CURRENT_LIMIT: CURRENT_LIMIT,
				IS_AUTO: IS_AUTO,
				IS_FORBIDDEN: IS_FORBIDDEN,
				BATERRY_TYPE: BATERRY_TYPE,
				RUN_STATUS: RUN_STATUS,
				UNDERVOL: UNDERVOL,
				UPVOL: UPVOL,
				HIGHTEM: HIGHTEM,
				PRESSURE: PRESSURE,
				MOS_STATUS: MOS_STATUS,
				BMS_STATUS: BMS_STATUS,
				IS_DOORS: IS_DOORS,
				IS_CHARGE: IS_CHARGE,
				CHARGE_CURRENT: CHARGE_CURRENT,
				OVER_CURRENT: OVER_CURRENT,
				VOL_LOSE: VOL_LOSE,
				NOTALLOW_CHARGE: NOTALLOW_CHARGE,
				BATTERY_ONLINE: BATTERY_ONLINE,
				LOAD_PROTECT: LOAD_PROTECT,
				UP_VOL_PROTECT: UP_VOL_PROTECT,
				CURRENT_LIMIT_WARN: CURRENT_LIMIT_WARN,
				CELL_HIGH_TEM: CELL_HIGH_TEM,
				ENVIR_LOW_TEM: ENVIR_LOW_TEM,
				ENVIR_HIGH_TEM: ENVIR_HIGH_TEM,
				MOS_HIGH_TEM: MOS_HIGH_TEM,
				LOW_VOL_PROTECT: LOW_VOL_PROTECT,
				INVERSE_PROTECT: INVERSE_PROTECT,
				BMS_SIGN: BMS_SIGN,
				MOS_PIPE_STATUS: MOS_PIPE_STATUS,
				BATTERY_ADJUST: BATTERY_ADJUST,
				BATTERY_STATUSING: BATTERY_STATUSING,
				BATTERY_CONTROL: BATTERY_CONTROL,
				DOOR_STATUS: DOOR_STATUS,
				BATTERY_ISON: BATTERY_ISON,
				DOOR_LOCK_SIGNAL: DOOR_LOCK_SIGNAL,
				CABIN_STATUS: CABIN_STATUS,
				RELAY_STATUS: RELAY_STATUS,
				CABIN_DOOR_STATUS: CABIN_DOOR_STATUS,
				POWER_SUPPLY_STATUS: POWER_SUPPLY_STATUS,
				SMOKE_DETECTOR: SMOKE_DETECTOR,
				WATER_OUT: WATER_OUT,

				// '控制'
				items: ["诊断", "参数", "版本查询"],
				current: 0,
				params: "",

				exportBtn: {
					width: "90%",
					position: "fixed",
					left: "5%",
					bottom: "140rpx",
				},
				percent: 10, //百分比0~100

				isDiagnosis: false, //诊断状态
				currentIndex: null, //当前仓号
				paramItems: [
					"主控单元",
					"仓控单元",
					"检测单元",
				], //参数模块

				command: 0, //命令字
				currentCollapse: 0, //当前折叠面板
				isProcess: false, //是否诊断中
				dgMessage: "", //检测状态提示信息

				masterControl: {
					//主控状态
					param1: "",
					param2: "",
					param3: "",
					param4: "",
					param5: "",
					param6: "",
					param7: "",
				},
				unitInfo: {
					//检测单元状态信息
					param1: undefined,
					param2: undefined,
					param3: undefined,
					param4: undefined,
					param5: undefined,
					param6: undefined,
					param7: undefined,
					param8: undefined,
					param9: undefined,
					param10: undefined,
					param11: undefined,
					param12: undefined,
					param13: undefined,
					param14: undefined,
					param15: undefined,
					param16: undefined,
					param17: undefined,
					param18: undefined,
					param19: undefined,
					param20: undefined,
					param21: undefined,
					param22: undefined,
					param23: undefined,
					param24: undefined,
					param25: undefined,
				},

				binStatus: {
					param1: "",
					param2: "",
					param3: "",
					param4: "",
					param5: "",
					param6: "",
					param7: "",
					param8: "",
					param9: "",
					param10: "",
					param11: "",
					param12: "",
					param13: "",
					param14: "",
					param15: "",
					param16: "",
					param17: "",
					param18: "",
					param19: "",
					param20: "",
					param21: "",
					param22: "",
					param23: "",
					param24: "",
					param25: "",
				},
			};
		},

		async onLoad(e) {		
			this.deviceInfo = JSON.parse(decodeURIComponent(e.deviceInfo));
			// 设备类型 CC:充电柜; CHZD:换电柜
			this.deviceType = (this.deviceInfo.localName && this.deviceInfo.localName.startsWith('CC') || this
					.deviceInfo.name && this.deviceInfo.name.startsWith('CC')) ?
				"CC" : 'CHZD';
			// 计算仓数
			this.binNum = this.computBInNum(this.deviceInfo.localName);

			// 监听之前是否有其他设备连接,是,断开连接,建立新连接;否,直接建立连接.
			// 若当前设备已连接连接,则不做操作
			if (this.curConnectBLE.length == 0) {
				try {
					this.$Toast.loading('连接中~');
					await this.connect(this.deviceInfo);
					await this.doAuth();

					//协商MTU
					this.setMaxMTU(this.deviceInfo.deviceId);
				} catch (err) {
					console.log(err)
					setTimeout(() => {
						this.goBack();
					}, 2000)

				}
			} else {
				let inx = this.curConnectBLE.findIndex(item => item.deviceId == this.deviceInfo.deviceId);
				if (inx == -1) {
					let datas = await this.$store.dispatch('closeBLEConnection', this.curConnectBLE[0].deviceId);
					if (datas) {
						this.$Toast.loading('连接中~');
						try {
							await this.connect(this.deviceInfo);
							await this.doAuth();

							// Android协商MTU
							this.setMaxMTU(this.deviceInfo.deviceId);
						} catch (err) {
							setTimeout(() => {
								this.goBack();
							}, 2000)
						}
					}
				}
			}
		},
		computed: {
			...mapState(['curConnectBLE', 'maxMTU']),
			// 柜控电源数量
			comCabinNum() {
				if (Number(this.binNum) < 16) {
					return 1;
				} else if (Number(this.binNum) >= 16 && Number(this.binNum) < 24) {
					return 2;
				} else {
					return 3;
				}
			},
			comColor() {
				return function(item) {
					if (item == 0) {
						return '#f56c6c';
					} else if (item == 1) {
						return '#19be6b'
					}
				}
			},
			comColor2() {
				return function(item) {
					if (item == 1) {
						return '#f56c6c';
					} else if (item == 0) {
						return '#19be6b'
					}
				}
			},
			detailYesOrNo() {
				return function(val) {
					if (val == 1) {
						return "是";
					} else if (val !== '' && val != 1) {
						return '否';
					} else {
						return '';
					}
				}
			},
		},
		watch: {
			'$store.state.curConnectBLE': {
				immediate: true,
				deep: true,
				handler(e) {},
			},
			'maxMTU': {
				immediate: true,
				deep: true,
				handler(e) {
					console.log('watch maxMTU值变化')
					console.log(e)
				},
			}
		},
		methods: {
			// 连接设备
			async connect(item) {
				try {
					await this.$store.dispatch('createBLEConnection', item)
					await this.$store.dispatch('checkDeviceService', {
						deviceId: item.deviceId,
						serviceId,
						characteristicId: characteristicId2
					})
					item.serviceId = serviceId
					item.characteristicId = characteristicId2
					this.deviceInfo = item
				} catch (err) {}
			},
			// 鉴权请求
			doAuth() {
				let that = this;
				// that.$Toast.loading('鉴权中~');
				// 向蓝牙设备发送数据
				let {
					deviceId,
				} = that.deviceInfo;
				const buffer = sendAuthString(authPassword);
				uni.writeBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					// 这里的value是ArrayBuffer类型
					value: buffer,
					success(res) {
						console.log('writeBLECharacteristicValue success', res.errMsg)
						console.log(res)
						console.log(res.errMsg)
						that.doAuthRead();
					},
					fail(err) {
						console.log(err)
						that.$Toast.none('鉴权失败！');
						setTimeout(() => {
							that.goBack();
						}, 2000)
					}
				})
			},
			doAuthRead() {
				let {
					deviceId,
				} = this.deviceInfo;
				let that = this;
				// 读取低功耗蓝牙设备的特征值的二进制数据值
				uni.readBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId: characteristicId1,
					success(res) {
						uni.onBLECharacteristicValueChange(function(res) {
							// console.log(
							// 	`characteristic ${res.characteristicId} has changed, now is ${res.value}`
							// )
							let value = res.value;
							console.log(value)
							// 第1字节为鉴权结果，后面6字节为毫秒时间戳，鉴权失败时时间戳返回为0
							let uint8Array = new Uint8Array(value);
							console.log('这是uint8Array--------')
							console.log(uint8Array)
							let newArray = Array.from(uint8Array);
							console.log('这是newArray=======')
							console.log(newArray)

							let start = newArray.slice(0, 1);
							let end = newArray.slice(1);
							console.log(start)
							console.log(end)
							if (start == 1) {
								that.$Toast.none('鉴权失败！');
								// setTimeout(() => {
								// 	that.goBack();
								// }, 2000)
							} else if (start == 0) {
								that.$Toast.none('鉴权成功！');
							}
						})

					},
					fail(fal) {
						console.log("读取数据数据失败", fal)
						that.$Toast.none('鉴权失败！');
						setTimeout(() => {
							that.goBack();
						}, 2000)
					}
				})
			},
			// ArrayBuffer 转字符串
			ab2str(data) {
				return String.fromCharCode.apply(null, new Uint8Array(data));
			},

			onClickItem(e) {
				if (this.current != e.currentIndex) {
					this.current = e.currentIndex;
				}
			},
			getValue(cpcl) {
				let characteristicValue = ab2hex(cpcl);
				let strValue = hexCharCodeToStr(characteristicValue)
				return strValue;
			},

			//通过下面的方法将html转换为图片base64数据回调给此处
			receiveRenderData(data) {
				let that = this;
				base64ToPath(data, '.jpeg').then(function(imgPath) {
					uni.showModal({
						title: JSON.stringify(imgPath),
					});
					//保存到手机相册,
					// #ifdef H5
					uni.downloadFile({
						url: imgPath,
						success: (res) => {
							//创建一个a标签
							var link = document.createElement('a');
							//把a标签的href属性赋值到生成好了的url
							link.href = imgPath;

							//通过a标签的download属性修改下载图片的名字
							link.download = '设备参数.png';
							// link.download = imgPath.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0];
							//让a标签的click函数，直接下载图片
							link.click();
							uni.hideLoading()
						}
					})
					// #endif
					// #ifndef H5
					that.saveImg(imgPath);
					// #endif

				})
			},
			saveImg(path) {
				uni.saveImageToPhotosAlbum({
					filePath: path,
					success: () => {
						uni.hideLoading();
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						})
					},
					fail: () => {
						uni.hideLoading();
						uni.getSetting({
							success: res => {
								if (!res.authSetting['scope.writePhotosAlbum']) {
									uni.showModal({
										title: '提示',
										content: '保存图片需要使用您的相册权限',
										cancelText: '拒绝',
										confirmText: '去授权',
										success: res => {
											if (res.confirm) {
												uni.openSetting();
											} else {
												uni.showToast({
													title: '无法保存图片',
													icon: 'none'
												})
											}
										}
									})
								}
							}
						})
					}
				})
			},
			// 复制
			isCopy(item) {
				doCopy(item.equipCode);
			},

			// 将十六进制格式的字符串转换成 ArrayBuffer
			hexToArrayBuffer(str) {
				let val = ""
				for (let i = 0; i < str.length; i++) {
					if (val === '') {
						val = str.charCodeAt(i).toString(16)
					} else {
						val += ',' + str.charCodeAt(i).toString(16)
					}
				}
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer;
			},

			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 断开连接
			async cancleConnect() {
				let res = await this.$store.dispatch('closeBLEConnection', this.deviceInfo.deviceId);
				// 断开成功,返回上一页
				if (res) {
					this.$Toast.none('连接已断开~');
					setTimeout(() => {
						this.goBack();
					}, 2000)
				}
			},
			// 协商MTU
			setMaxMTU(deviceId) {
				let that = this;
				let platform = uni.getSystemInfoSync().platform;
				switch (platform) {
					case "android":
						uni.setBLEMTU({
							deviceId: deviceId,
							mtu: 512,
							success(res) {
								console.log("设置最大值成功========")
								console.log(res)
							}
						})
						// 若设置失败,会分配一个合适的MTU
						uni.onBLEMTUChange(function(res) {
							console.log('bluetooth mtu is::::::::', res.mtu)
							console.log(res)
							that.$store.commit("setMaxMTU", res.mtu);
						})
						break;
					case "ios":
						uni.getBLEMTU({
							deviceId: deviceId,
							success: res => {
								console.log(res)
								that.$store.commit("setMaxMTU", res.mtu);
							},
							fail: err => {
								console.log('获取MTU失败:', err);
							}
						});
						break;
				}
			},
			// 计算仓数
			computBInNum(str) {
				const regex = /\d/;
				const match = str.match(regex);
				if (match) {
					const index = match.index;
					const result = str.substr(index, 2);
					return result;
				}
			},

			closeBinpopup(pop) {
				this.$refs[pop].close();
			},
			// 参数详情
			goPage(index) {
				let url =
					this.current == 1 ?
					`/pagesA/charge/param/param` :
					`/pagesA/charge/version/index`;
				uni.navigateTo({
					url: `${url}?type=${index}&binNum=${
			  this.binNum
			}&deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`,
				});
			},
			goControl(index) {
				uni.navigateTo({
					url: `/pagesA/bluetooth/control?type=${index}&binNum=${
			  this.binNum
			}deviceInfo=${encodeURIComponent(JSON.stringify(this.deviceInfo))}`,
				});
			},
		}
	};
</script>
<style>
	page {
		background-color: #eff0f1 !important;
	}
</style>
<style lang="scss" scoped>
	@import "@/static/iconfont.css";
	@import "@/pagesA/bluetooth/index.scss";
</style>